﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using CRM.Extensions;
using CRM.Models;
using CRM.ViewModels.Customer;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Z.EntityFramework.Plus;

namespace CRM.Services.Customer
{
    using CustomerModel = Models.Customer;
    public class CustomerService : BaseService
    {
        private readonly MyDbContext _dbContext;
        private readonly ILogger<CustomerService> _logger;

        public CustomerService(MyDbContext dbContext, ILogger<CustomerService> logger)
        {
            _dbContext = dbContext;
            _logger = logger;
        }

        /// <summary>
        /// 批量添加
        /// </summary>
        /// <param name="customers"></param>
        /// <returns></returns>
        public async Task<bool> Create(IEnumerable<Models.Customer> customers)
        {
            var duplicate = await _dbContext.Customer
                .Where(m => customers.Select(c => c.Email).Contains(m.Email))
                // 暂时改为对自己添加的客户进行去重，而不是根据oem
                .Where(m => m.OemId == CurrentUser.OemId && m.UserId == CurrentUser.Id)
                .Select(m => m.Email)
                .ToListAsync();
            var filteredCustomers = customers.Where(c => !duplicate.Contains(c.Email)).ToList();
            if (filteredCustomers.Count == 0)
            {
                Error = "客户数据重复添加";
                _logger.LogInformation("All customers are duplicate in oem, skip add customer.");
                return false;
            }

            foreach (var filteredCustomer in filteredCustomers)
            {
                FillCustomer(filteredCustomer);
                _dbContext.Customer.Add(filteredCustomer);
            }

            var status = await _dbContext.SaveChangesAsync();
            if (status > 0)
            {
                return true;
            }

            Error = "创建失败";
            return false;
        }

        public async Task<bool> Create(Models.Customer customer)
        {
            var user = CurrentUser;

            if (user.Company.IsRepetitionAllowed == Company.IsRepetitionAllowedType.ENABLE)
            {
                var repeat = await DbContext.Customer.Where(m => m.Email == customer.Email && m.OemId == user.OemId)
                               .Take(1).CountAsync();

                if (repeat > 0)
                {
                    return false;
                }
            }

            if (string.IsNullOrEmpty(customer.Name))
            {
                Error = "参数丢失: Name";
                return false;
            }

            if (string.IsNullOrEmpty(customer.Email))
            {
                Error = "参数丢失: Email";
                return false;
            }

            if (Helper.CheckEmail(customer.Email))
            {
                Error = "邮箱非法";
                return false;
            }


            FillCustomer(customer);
            DbContext.Customer.Add(customer);

            var status = await DbContext.SaveChangesAsync();
            if (status == 1)
            {
                return true;
            }

            Error = "创建失败";
            return false;
        }

        private void FillCustomer(Models.Customer customer, User currentUser = null, DateTime? staticTime = null)
        {
            var time = staticTime ?? DateTime.Now;
            var user = currentUser ?? CurrentUser;

            customer.UpdatedAt = time;
            customer.CreatedAt = time;
            customer.UserId = user.Id;
            customer.OemId = user.OemId;
            customer.CompanyId = user.CompanyId;
            customer.UserGroupId = user.GroupId;
            customer.SourceId = customer.SourceId == 0 ? null : customer.SourceId;
            customer.GroupId = customer.GroupId == 0 ? null : customer.GroupId;

            if (customer.Origin == 1)
            {
                customer.BelongUserId = user.Id;
                customer.BelongAt = time;
            }
        }

        public async Task<int> CreateBlockReturnId(Models.CustomerCompany customerCompany)
        {
            var user = CurrentUser;

            FillCustomerCompany(customerCompany);
            DbContext.CustomerCompany.Add(customerCompany);

            var status = await DbContext.SaveChangesAsync();
            if (status >= 1)
            {
                DbContext.Entry(customerCompany);
                return customerCompany.Id;
            }

            Error = "创建失败";
            return 0;
        }

        public async Task<bool> CreateBlock(Models.CustomerCompany customerCompany, bool IsNeedCheckRepeat = false)
        {
            var user = CurrentUser;
            customerCompany.NameHash = customerCompany.Name.GetFixedHashCode();

            if (IsNeedCheckRepeat)
            {
                var Model = CustomerCompanyCondition();
                var repeat = await Model.Where(m => m.NameHash == customerCompany.NameHash && m.From == customerCompany.From).FirstOrDefaultAsync();


                if (repeat != null)
                {
                    Error = "数据已存在";
                    return false;
                }

            }

            FillCustomerCompany(customerCompany);
            DbContext.CustomerCompany.Add(customerCompany);

            var status = await DbContext.SaveChangesAsync();
            if (status == 1)
            {
                return true;
            }

            Error = "创建失败";
            return false;
        }

        private void FillCustomerCompany(Models.CustomerCompany CustomerCompany, User currentUser = null, DateTime? staticTime = null)
        {
            var time = staticTime ?? DateTime.Now;
            var user = currentUser ?? CurrentUser;

            CustomerCompany.UpdatedAt = time;
            CustomerCompany.CreatedAt = time;
            CustomerCompany.UserId = user.Id;
            CustomerCompany.OemId = user.OemId;
            CustomerCompany.CompanyId = user.CompanyId;
            CustomerCompany.GroupId = user.GroupId;
            CustomerCompany.SourceId = CustomerCompany.SourceId == 0 ? null : CustomerCompany.SourceId;
            CustomerCompany.DiyGroupId = CustomerCompany.DiyGroupId == 0 ? null : CustomerCompany.DiyGroupId;
        }


        public enum SetDataType
        {
            [Description("块")]
            Block,
            [Description("客户")]
            Customer
        }

        public async Task<bool> SetGroup(int GroupId, List<int> Ids, SetDataType Type = SetDataType.Customer)
        {

            if (GroupId <= 0)
            {
                Error = "参数错误";
                return false;
            }

            if (Ids.Count <= 0)
            {
                Error = "参数错误!";
                return false;
            }

            var user = await UserManager.GetUserAsync(HttpContext.User);

            var Row = await DbContext.CustomerGroup.Where(m => m.Id == GroupId && m.OemId == user.OemId)
                .FirstOrDefaultAsync();

            if (Row == null)
            {
                Error = "分组不存在";
                return false;
            }


            bool res = false;

            if (Type == SetDataType.Customer)
            {
                var List = await DbContext.Customer.Where(m => Ids.Contains(m.Id) && m.OemId == user.OemId).ToListAsync();

                if (List.Count <= 0 || List.Count != Ids.Count)
                {
                    Error = "数据不存在";
                    return false;
                }
                res = await SetGroupDB(DbContext.CustomerGroup, List, Row, GroupId);
            }
            else
            {
                var List = await DbContext.CustomerCompany.Where(m => Ids.Contains(m.Id) && m.OemId == user.OemId).ToListAsync();

                if (List.Count <= 0 || List.Count != Ids.Count)
                {
                    Error = "数据不存在";
                    return false;
                }
                res = await SetGroupDB(List, GroupId);
            }

            return res;

        }
        private async Task<bool> SetGroupDB(List<CustomerCompany> List, int GroupId)
        {
            foreach (var item in List)
            {
                item.DiyGroupId = GroupId;
            }
            var Transaction = DbContext.Database.BeginTransaction();
            try
            {
                await DbContext.SaveChangesAsync();
                Transaction.Commit();
            }
            catch (Exception e)
            {
                Transaction.Rollback();
                Error = e.Message;
                return false;
            }

            return true;
        }
        private async Task<bool> SetGroupDB(DbSet<CustomerGroup> customerGroup, List<CustomerModel> List, CustomerGroup Row, int GroupId)
        {
            var user = await UserManager.GetUserAsync(HttpContext.User);

            List<CustomerOperationLog> logs = new() { };

            foreach (var item in List)
            {
                if (item.GroupId != GroupId)
                {

                    var GroupInfo = await customerGroup.Where(m => m.Id == GroupId && m.OemId == user.OemId)
                    .FirstOrDefaultAsync();
                    var Content = "";
                    if (GroupInfo != null && item.GroupId != null)
                    {
                        Content = $"将客户分组 由{GroupInfo.Name}修改为{Row.Name}。";
                    }
                    else
                    {
                        Content = $"将客户分组 由未分组修改为{Row.Name}。";
                    }

                    logs.Add(
                        new CustomerOperationLog()
                        {
                            CustomerId = item.Id,
                            Content = Content,
                        }
                    );
                }

                item.GroupId = GroupId;
            }

            var Transaction = DbContext.Database.BeginTransaction();
            try
            {
                await DbContext.SaveChangesAsync();
                if (logs.Count > 0)
                {
                    await (new OperationLogService(DbContext, HttpContext, UserManager)).AddLogAsync(logs);
                }

                Transaction.Commit();
            }
            catch (Exception e)
            {
                Transaction.Rollback();
                Error = e.Message;
                return false;
            }

            return true;
        }

        public async Task<bool> SetSource(int SourceId, List<int> Ids, SetDataType Type = SetDataType.Customer)
        {
            if (SourceId <= 0)
            {
                Error = "参数错误";
                return false;
            }

            if (Ids.Count <= 0)
            {
                Error = "参数错误!";
                return false;
            }

            var user = await UserManager.GetUserAsync(HttpContext.User);

            var Row = await DbContext.CustomerSource.Where(m => m.Id == SourceId && m.OemId == user.OemId)
                .FirstOrDefaultAsync();

            if (Row == null)
            {
                Error = "来源不存在";
                return false;
            }
            bool res = false;

            if (Type == SetDataType.Customer)
            {
                var List = await DbContext.Customer.Where(m => Ids.Contains(m.Id) && m.OemId == user.OemId).ToListAsync();

                if (List.Count <= 0 || List.Count != Ids.Count)
                {
                    Error = "数据不存在";
                    return false;
                }
                res = await SetSourceDB(DbContext.CustomerSource, List, Row, SourceId);
            }
            else
            {
                var List = await DbContext.CustomerCompany.Where(m => Ids.Contains(m.Id) && m.OemId == user.OemId).ToListAsync();

                if (List.Count <= 0 || List.Count != Ids.Count)
                {
                    Error = "数据不存在";
                    return false;
                }
                res = await SetSourceDB(List, SourceId);
            }

            return res;
        }
        private async Task<bool> SetSourceDB(List<CustomerCompany> List, int SourceId)
        {
            foreach (var item in List)
            {
                item.SourceId = SourceId;
            }
            var Transaction = DbContext.Database.BeginTransaction();
            try
            {
                await DbContext.SaveChangesAsync();
                Transaction.Commit();
            }
            catch (Exception e)
            {
                Transaction.Rollback();
                Error = e.Message;
                return false;
            }

            return true;
        }
        private async Task<bool> SetSourceDB(DbSet<CRM.Models.CustomerSource> customerSource, List<CustomerModel> List, CRM.Models.CustomerSource Row, int SourceId)
        {
            var user = await UserManager.GetUserAsync(HttpContext.User);

            List<CustomerOperationLog> logs = new() { };

            foreach (var item in List)
            {
                if (item.SourceId != SourceId)
                {
                    var SourceInfo = await customerSource
                        .Where(m => m.Id == SourceId && m.OemId == user.OemId).FirstOrDefaultAsync();
                    var content = "";
                    if (SourceInfo != null && item.SourceId != null)
                    {
                        content = $"将客户来源 由{SourceInfo.Name}修改为{Row.Name}。";
                    }
                    else
                    {
                        content = $"将客户来源 由无修改为{Row.Name}。";
                    }

                    logs.Add(
                        new CustomerOperationLog()
                        {
                            CustomerId = item.Id,
                            Content = content,
                        }
                    );
                }

                item.SourceId = SourceId;
            }

            var Transaction = DbContext.Database.BeginTransaction();
            try
            {
                await DbContext.SaveChangesAsync();
                if (logs.Count > 0)
                {
                    await (new OperationLogService(DbContext, HttpContext, UserManager)).AddLogAsync(logs);
                }

                Transaction.Commit();
            }
            catch (Exception e)
            {
                Transaction.Rollback();
                Error = e.Message;
                return false;
            }
            return true;
        }



        public async Task<bool> SetLabel(List<int> LabelIds, List<int> Ids, SetDataType Type = SetDataType.Customer)
        {
            if (LabelIds.Count < 0)
            {
                Error = "请选择标签";
                return false;
            }

            if (Ids.Count < 0)
            {
                Error = "请选择需要操作的数据";
                return false;
            }

            var user = await UserManager.GetUserAsync(HttpContext.User);



            var LabelList = await DbContext.CustomerLabel.Where(m => LabelIds.Contains(m.Id) && m.OemId == user.OemId)
                .ToListAsync();
            if (LabelList.Count <= 0 || LabelIds.Count != LabelList.Count)
            {
                Error = "标签不存在";
                return false;
            }

            bool res = false;

            if (Type == SetDataType.Customer)
            {
                var List = await DbContext.Customer.Where(m => Ids.Contains(m.Id) && m.OemId == user.OemId)
                 .Include(m => m.Labels).ToListAsync();
                if (List.Count <= 0 || LabelIds.Count != List.Count)
                {
                    Error = "数据不存在";
                    return false;
                }

                res = await SetLabelDB(List, LabelList);

            }
            else
            {
                var List = await DbContext.CustomerCompany.Where(m => Ids.Contains(m.Id) && m.OemId == user.OemId)
                 .Include(m => m.Labels).ToListAsync();
                if (List.Count <= 0 || LabelIds.Count != List.Count)
                {
                    Error = "数据不存在";
                    return false;
                }

                res = await SetLabelDB(List, LabelList);
            }

            return res;

        }
        private async Task<bool> SetLabelDB(List<CustomerModel> List, List<CRM.Models.CustomerLabel> LabelList)
        {
            foreach (var Item in List)
            {
                Item.Labels = LabelList;
            }

            var Transaction = DbContext.Database.BeginTransaction();
            try
            {
                await DbContext.SaveChangesAsync();

                Transaction.Commit();
            }
            catch (Exception e)
            {
                Transaction.Rollback();
                Error = e.Message;
                return false;
            }

            return true;
        }
        private async Task<bool> SetLabelDB(List<CustomerCompany> List, List<CRM.Models.CustomerLabel> LabelList)
        {
            foreach (var Item in List)
            {
                Item.Labels = LabelList;
            }

            var Transaction = DbContext.Database.BeginTransaction();
            try
            {
                await DbContext.SaveChangesAsync();

                Transaction.Commit();
            }
            catch (Exception e)
            {
                Transaction.Rollback();
                Error = e.Message;
                return false;
            }

            return true;
        }


        public async Task<bool> SetIsIntention(int IsIntention, List<int> Ids, SetDataType Type = SetDataType.Customer)
        {

            var IsCustomer = Type == SetDataType.Customer;
            var IsBlock = Type == SetDataType.Block;

            var CheckValue = new List<int>() { 0, 1 };

            if (!CheckValue.Contains(IsIntention))
            {
                Error = "参数错误";
                return false;
            }

            var user = await UserManager.GetUserAsync(HttpContext.User);

            List<CustomerModel> List = new() { };

            if (IsCustomer)
            {
                List = await DbContext.Customer.Where(m => Ids.Contains(m.Id) && m.OemId == user.OemId).ToListAsync();

                if (List.Count <= 0 || List.Count != Ids.Count)
                {
                    Error = "客户不存在";
                    return false;
                }
            }

            if (IsBlock)
            {
                List = await DbContext.Customer.Where(m => Ids.Contains(m.BlockId) && m.OemId == user.OemId).ToListAsync();
            }

            List<CustomerOperationLog> logs = new() { };
            var BlockId = 0;

            foreach (var Item in List)
            {
                if (Item.IsIntention != IsIntention)
                {
                    CustomerModel.IsIntentionEnum OldEnum = (CustomerModel.IsIntentionEnum)Item.IsIntention;
                    CustomerModel.IsIntentionEnum NewEnum = (CustomerModel.IsIntentionEnum)IsIntention;
                    var Content = $"将客户意向状态 由{OldEnum}修改为{NewEnum}。";
                    logs.Add(
                        new CustomerOperationLog()
                        {
                            CustomerId = Item.Id,
                            Content = Content,
                        }
                    );
                }
                if (IsCustomer)
                {
                    BlockId = Item.BlockId;
                }
                Item.IsIntention = IsIntention;
            }

            var Transaction = DbContext.Database.BeginTransaction();
            try
            {
                if (logs.Count > 0)
                {
                    await (new OperationLogService(DbContext, HttpContext, UserManager)).AddLogAsync(logs);
                }
                if (IsCustomer)
                {
                    //设置有意向同时修改块
                    if (IsIntention == 1 && BlockId > 0)
                    {
                        DbContext.CustomerCompany.Where(m => m.Id == BlockId).Update(m => new { IsExistIntention = CustomerCompany.IsExistIntentionType.Yes });

                    }
                    //设置无意向同时修改块
                    if (IsIntention == 0 && BlockId > 0)
                    {
                        var Num = DbContext.Customer.Where(m => m.BlockId == BlockId && m.OemId == user.OemId && m.IsIntention == 1).Count();
                        if (Num == 0)
                        {
                            DbContext.CustomerCompany.Where(m => m.Id == BlockId).Update(m => new { IsExistIntention = CustomerCompany.IsExistIntentionType.NO });
                        }

                    }
                }

                if (IsBlock)
                {
                    if (IsIntention == 1)
                    {
                        DbContext.CustomerCompany.Where(m => Ids.Contains(m.Id)).Update(m => new { IsExistIntention = CustomerCompany.IsExistIntentionType.Yes });
                    }

                    if (IsIntention == 0)
                    {
                        DbContext.CustomerCompany.Where(m => Ids.Contains(m.Id)).Update(m => new { IsExistIntention = CustomerCompany.IsExistIntentionType.NO });
                    }
                }
                await DbContext.SaveChangesAsync();
                Transaction.Commit();
            }
            catch (Exception e)
            {
                Transaction.Rollback();
                Error = e.Message;
                return false;
            }

            return true;
        }

        public async Task<int> SetOrGetBlockId(CustomerCompany customerCompany)
        {
            var NameHash = customerCompany.NameHash;

            var Model = CustomerCompanyCondition();
            var row = await Model.Where(m => m.NameHash == NameHash && m.From == customerCompany.From).FirstOrDefaultAsync();

            if (row != null)
            {
                return row.Id;
            }
            customerCompany.Id = 0;
            return await CreateBlockReturnId(customerCompany);
        }

        public async Task<bool> SetIsPrivate(int IsPrivate, List<int> Ids, CustomerCompany BlockInfo)
        {

            var CheckValue = new List<int>() { 0, 1 };

            if (!CheckValue.Contains(IsPrivate))
            {

                Error = "参数错误";
                return false;
            }

            var user = await UserManager.GetUserAsync(HttpContext.User);

            IQueryable<CustomerModel> Model;

            if (IsPrivate == 0)
            {
                Model = CustomnerCondition();
            }
            else
            {
                Model = CustomnerCondition(true);
            }

            var List = await Model.Where(m => Ids.Contains(m.Id)).ToListAsync();

            if (List.Count <= 0 || List.Count != Ids.Count)
            {
                Error = "客户不存在";
                return false;
            }

            List<CustomerOperationLog> logs = new() { };

            foreach (var Item in List)
            {
                if (Item.IsPrivate != IsPrivate)
                {
                    var Content = "";

                    if (IsPrivate == 1)
                    {
                        Content = "从公海认领客户";
                    }

                    if (IsPrivate == 0)
                    {
                        Content = "将客户移入公海";
                    }

                    logs.Add(
                        new CustomerOperationLog()
                        {
                            CustomerId = Item.Id,
                            Content = Content,
                        }
                    );
                }

                Item.IsPrivate = IsPrivate;
                Item.IsIntention = 0;

                //认领客户 初始化操作
                if (IsPrivate == 1)
                {
                    Item.BelongAt = DateTime.Now;
                    Item.BelongUserId = user.Id;
                    Item.Attention = 0;
                    Item.GroupId = null;
                    Item.SourceId = null;
                    Item.Labels = null;
                }
            }

            var Transaction = DbContext.Database.BeginTransaction();
            try
            {
                var BlockId = await SetOrGetBlockId(BlockInfo);

                if (BlockId < 0)
                {
                    throw new Exception("数据创建失败");
                }

                foreach (var Item in List)
                {
                    Item.BlockId = BlockId;
                }

                if (logs.Count > 0)
                {
                    await (new OperationLogService(DbContext, HttpContext, UserManager)).AddLogAsync(logs);
                }

                IQueryable<CustomerCompany> BlockModel = CustomerCompanyCondition();

                //移入公海同时修改块
                if (IsPrivate == 0 && BlockId > 0)
                {
                    BlockModel.Where(m => m.Id == BlockId).Update(m => new { IsExistPrivate = CustomerCompany.IsExistPrivateType.Yes });

                    //块下面的客户是否全处于公海
                    var IsPrivateNum = Model.Where(m => m.BlockId == BlockId && m.IsPrivate == 1).Count();
                    if (IsPrivateNum == 0)
                    {
                        BlockModel.Where(m => m.Id == BlockId).Update(m => new { IsExistMy = CustomerCompany.IsExistMyType.NO });
                    }
                    //块下面的客户是否还存在意向客户
                    var IsIntentionNum = Model.Where(m => m.BlockId == BlockId && m.IsIntention == 1).Count();
                    if (IsIntentionNum == 0)
                    {
                        BlockModel.Where(m => m.Id == BlockId).Update(m => new { IsExistIntention = CustomerCompany.IsExistIntentionType.NO });
                    }

                }

                //认领客户同时修改块
                if (IsPrivate == 1 && BlockId > 0)
                {
                    var Num = Model.Where(m => m.BlockId == BlockId && m.IsPrivate == 0).Count();
                    if (Num == 0)
                    {
                        BlockModel.Where(m => m.Id == BlockId).Update(m => new { IsExistPrivate = CustomerCompany.IsExistPrivateType.NO });
                    }

                    DbContext.CustomerCompany.Where(m => m.Id == BlockId).Update(m => new { IsExistMy = CustomerCompany.IsExistMyType.Yes });

                }

                await DbContext.SaveChangesAsync();
                Transaction.Commit();

            }
            catch (Exception e)
            {
                Transaction.Rollback();
                Error = e.Message;
                return false;
            }

            return true;
        }




        public IQueryable<CustomerCompany> BlockSelectionRange(CustomerListVM.ActionType Action, int? Type)
        {
            var UserType = CurrentUser.Type;

            IQueryable<CustomerCompany> Model;

            if (Action == CustomerListVM.ActionType.Water)
            {
                Model = CustomerCompanyCondition(true);
            }
            else
            {
                Model = CustomerCompanyCondition();
            }


            if (Type > 0)
            {
                var type = (CustomerCompany.FromType)Type;
                Model = Model.Where(m => m.From == type);
            }

            var actionArr = Enum.GetValues(typeof(CustomerListVM.ActionType)).ToArrayDynamic();

            if (actionArr.Contains(Action))
            {

                //我的客户
                if (Action == CustomerListVM.ActionType.My)
                {
                    CustomerCompany.IsExistMyType isExistMy = CustomerCompany.IsExistMyType.Yes;
                    Model = Model.Where(m => m.IsExistMy == isExistMy);
                }
                //意向客户
                if (Action == CustomerListVM.ActionType.Intention)
                {
                    CustomerCompany.IsExistIntentionType ExistIntention = CustomerCompany.IsExistIntentionType.Yes;
                    Model = Model.Where(m => m.IsExistIntention == ExistIntention);
                }
                //公海客户
                if (Action == CustomerListVM.ActionType.Water)
                {
                    CustomerCompany.IsExistPrivateType ExistPrivate = CustomerCompany.IsExistPrivateType.Yes;
                    Model = Model.Where(m => m.IsExistPrivate == ExistPrivate);
                }

            }
            else
            {
                Error = "块类型错误";
            }
            return Model;
        }

        public IQueryable<CustomerModel> CustomerSelectionRange(CustomerListVM Scope)
        {
            IQueryable<CustomerModel> Model;

            if (Scope.Action == CustomerListVM.ActionType.Water)
            {
                Model = CustomnerCondition(true);
            }
            else
            {
                Model = CustomnerCondition();
            }


            //我的客户
            if (Scope.Action == CustomerListVM.ActionType.My)
            {
                Model = Model.Where(m => m.IsPrivate == 1 && m.BlockId == Scope.BlockId);
            }
            //意向客户
            if (Scope.Action == CustomerListVM.ActionType.Intention)
            {
                Model = Model.Where(m => m.IsIntention == 1 && m.IsPrivate == 1 && m.BlockId == Scope.BlockId);
            }
            //公海客户
            if (Scope.Action == CustomerListVM.ActionType.Water)
            {
                Model = Model.Where(m => m.IsPrivate == 0 && m.BlockId == Scope.BlockId);
            }



            if (Scope.Type > 0)
            {
                Model = Model.Where(m => (int)m.Type == Scope.Type);
            }
            if (!string.IsNullOrEmpty(Scope.Name))
            {
                Model = Model.Where(m => m.Name == Scope.Name);
            }
            if (!string.IsNullOrEmpty(Scope.Mobile))
            {
                Model = Model.Where(m => m.Mobile == Scope.Mobile);
            }
            var statusArr = new List<int> { 0, 1 };

            if (statusArr.Contains(Scope.Status))
            {
                Model = Model.Where(m => m.DealStatus == Scope.Status);
            }
            else if (Scope.Status == 2)
            {
                Model = Model.Where(m => m.FollowAt != null);
            }
            else if (Scope.Status == 3)
            {
                Model = Model.Where(m => m.FollowAt == null);
            }

            return Model;
        }

        public IQueryable<CustomerModel> CustomnerCondition(bool IsWater = false)
        {

            var UserType = CurrentUser.Type;

            var Model = DbContext.Customer as IQueryable<CustomerModel>;

            Model = Model.Where(m => m.OemId == CurrentUser.OemId);

            //公司管理员
            if (UserType == User.Types.CompanyAdmin || UserType == User.Types.Employee)
            {
                Model = Model.Where(m => m.CompanyId == CurrentUser.CompanyId);
            }

            if (!IsWater)
            {
                //员工
                if (UserType == User.Types.Employee)
                {
                    Model = Model.Where(m => m.BelongUserId == CurrentUser.Id);
                }
            }

            return Model;
        }

        public IQueryable<CustomerCompany> CustomerCompanyCondition(bool IsWater = false)
        {

            var UserType = CurrentUser.Type;

            var Model = DbContext.CustomerCompany as IQueryable<CustomerCompany>;

            Model = Model.Where(m => m.OemId == CurrentUser.OemId);

            //公司管理员
            if (UserType == User.Types.CompanyAdmin || UserType == User.Types.Employee)
            {
                Model = Model.Where(m => m.CompanyId == CurrentUser.CompanyId);
            }

            if (!IsWater)
            {
                //员工
                if (UserType == User.Types.Employee)
                {
                    Model = Model.Where(m => m.UserId == CurrentUser.Id);
                }

            }

            return Model;
        }


        public IQueryable<CustomerGroup> GroupCondition()
        {
            var UserType = CurrentUser.Type;

            var Model = DbContext.CustomerGroup as IQueryable<CustomerGroup>;

            Model = Model.Where(m => m.OemId == CurrentUser.OemId);

            //公司管理员
            if (UserType == User.Types.CompanyAdmin || UserType == User.Types.Employee)
            {
                Model = Model.Where(m => m.CompanyId == CurrentUser.CompanyId);
            }

            //员工
            if (UserType == User.Types.Employee)
            {
                Model = Model.Where(m => m.UserId == CurrentUser.Id);
            }

            return Model;
        }

        public IQueryable<CRM.Models.CustomerSource> SoureCondition()
        {
            var UserType = CurrentUser.Type;

            var Model = DbContext.CustomerSource as IQueryable<CRM.Models.CustomerSource>;

            Model = Model.Where(m => m.OemId == CurrentUser.OemId);

            //公司管理员
            if (UserType == User.Types.CompanyAdmin || UserType == User.Types.Employee)
            {
                Model = Model.Where(m => m.CompanyId == CurrentUser.CompanyId);
            }

            //员工
            if (UserType == User.Types.Employee)
            {
                Model = Model.Where(m => m.UserId == CurrentUser.Id);
            }

            return Model;
        }

        public IQueryable<CRM.Models.CustomerLabel> LabelCondition()
        {
            var UserType = CurrentUser.Type;

            var Model = DbContext.CustomerLabel as IQueryable<CRM.Models.CustomerLabel>;

            Model = Model.Where(m => m.OemId == CurrentUser.OemId);

            //公司管理员
            if (UserType == User.Types.CompanyAdmin || UserType == User.Types.Employee)
            {
                Model = Model.Where(m => m.CompanyId == CurrentUser.CompanyId);
            }

            //员工
            if (UserType == User.Types.Employee)
            {
                Model = Model.Where(m => m.UserId == CurrentUser.Id);
            }

            return Model;
        }
    }
}
